package com.mindskip.xzs.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.domain.Level;
import com.mindskip.xzs.domain.other.KeyValue;
import com.mindskip.xzs.domain.User;
import com.mindskip.xzs.domain.UserEventLog;
import com.mindskip.xzs.domain.enums.UserStatusEnum;
import com.mindskip.xzs.service.AuthenticationService;
import com.mindskip.xzs.service.LevelService;
import com.mindskip.xzs.service.UserEventLogService;
import com.mindskip.xzs.service.UserService;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.viewmodel.admin.user.*;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.github.pagehelper.PageInfo;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;


/**
 * @author 福安诚码科技有限公司
 */
@RestController("AdminUserController")
@RequestMapping(value = "/api/admin/user")
public class UserController extends BaseApiController {
    private final LevelService levelService;
    private final UserService userService;
    private final UserEventLogService userEventLogService;
    private final AuthenticationService authenticationService;

    @Autowired
    public UserController(UserService userService, UserEventLogService userEventLogService, AuthenticationService authenticationService, LevelService levelService) {
        this.userService = userService;
        this.userEventLogService = userEventLogService;
        this.authenticationService = authenticationService;
        this.levelService = levelService;
    }


    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserResponseVM>> pageList(@RequestBody UserPageRequestVM model) {
        if(null != model.getLevelName()){
            model.setUserLevel(model.getLevelName());
        }
        PageInfo<User> pageInfo = userService.userPage(model);
        PageInfo<UserResponseVM> page = PageInfoHelper.copyMap(pageInfo, d -> UserResponseVM.from(d));
        return RestResponse.ok(page);
    }


    @RequestMapping(value = "/event/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserEventLogVM>> eventPageList(@RequestBody UserEventPageRequestVM model) {
        PageInfo<UserEventLog> pageInfo = userEventLogService.page(model);
        PageInfo<UserEventLogVM> page = PageInfoHelper.copyMap(pageInfo, d -> {
            UserEventLogVM vm = modelMapper.map(d, UserEventLogVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(d.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> select(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);
    }

    @RequestMapping(value = "/current", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> current() {
        User user = getCurrentUser();
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);
    }


    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<User> edit(@RequestBody @Valid UserCreateVM model) {
        model.setUserLevel(model.getLevel());
        //create
        if (model.getId() == null) {
            User existUser = userService.getUserByUserName(model.getUserName());
            if (null != existUser) {
                return new RestResponse<>(2, "用户已存在");
            }

            if (StringUtils.isBlank(model.getPassword())) {
                return new RestResponse<>(3, "密码不能为空");
            }
        }
        if (StringUtils.isBlank(model.getBirthDay())) {
            model.setBirthDay(null);
        }
        User user = modelMapper.map(model, User.class);
        user.setEducation(user.getEducationStr(user.getEducation()));
        user.setArmy(user.getArmyStr(user.getArmy()));
        user.setPolitics(user.getPoliticsStr(user.getPolitics()));
        if (model.getId() == null) {
            String encodePwd = authenticationService.pwdEncode(model.getPassword());
            user.setPassword(encodePwd);
            user.setUserUuid(UUID.randomUUID().toString());
            user.setCreateTime(new Date());
            user.setLastActiveTime(new Date());
            user.setDeleted(false);
            userService.insertByFilter(user);
        } else {
            if (!StringUtils.isBlank(model.getPassword())) {
                String encodePwd = authenticationService.pwdEncode(model.getPassword());
                user.setPassword(encodePwd);
            }
            user.setModifyTime(new Date());
            userService.updateByIdFilter(user);
        }
        return RestResponse.ok(user);
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public RestResponse update(@RequestBody @Valid UserUpdateVM model) {
        User user = userService.selectById(getCurrentUser().getId());
        modelMapper.map(model, user);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }


    @RequestMapping(value = "/changeStatus/{id}", method = RequestMethod.POST)
    public RestResponse<Integer> changeStatus(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        UserStatusEnum userStatusEnum = UserStatusEnum.fromCode(user.getStatus());
        Integer newStatus = userStatusEnum == UserStatusEnum.Enable ? UserStatusEnum.Disable.getCode() : UserStatusEnum.Enable.getCode();
        user.setStatus(newStatus);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);
        return RestResponse.ok(newStatus);
    }


    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        user.setDeleted(true);
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }


    @RequestMapping(value = "/selectByUserName", method = RequestMethod.POST)
    public RestResponse<List<KeyValue>> selectByUserName(@RequestBody String userName) {
        List<KeyValue> keyValues = userService.selectByUserName(userName);
        return RestResponse.ok(keyValues);
    }

    @RequestMapping(value = "/selectByLevel", method = RequestMethod.GET)
    public RestResponse<List<Level>> selectByLevel() {
        List<Level> keyValues = levelService.getLevelList();
        return RestResponse.ok(keyValues);
    }

    /**
     * 用户excel导出
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/page/list/excel", method = RequestMethod.GET)
    public void pageListExcel(String phone, String userName,Integer levelName, HttpServletResponse response) {
        UserPageRequestVM model = new UserPageRequestVM();
        model.setPageIndex(0);
        model.setPageSize(10000);
        model.setPhone(phone);
        model.setUserName(userName);
        model.setUserLevel(levelName);
        PageInfo<User> pageInfo = userService.userPage(model);
        List<User> userList = pageInfo.getList();
        //userList = getUserList(userList);
        if (CollUtil.isNotEmpty(userList)) {
            ExcelWriter writer = ExcelUtil.getWriter();
            //自定义标题别名
            writer.setOnlyAlias(true);
            writer.addHeaderAlias("userName", "昵称");
            writer.addHeaderAlias("realName", "真实姓名");
            writer.addHeaderAlias("sexStr", "性别");
            writer.addHeaderAlias("phone", "电话");
            writer.addHeaderAlias("userLevel", "班级");
            writer.addHeaderAlias("idCardNo", "身份证号码");
            writer.addHeaderAlias("nationality", "民族");
            writer.addHeaderAlias("location", "住址");
            writer.addHeaderAlias("education", "教育");
            writer.addHeaderAlias("health", "健康状态");
            writer.addHeaderAlias("birthLocation", "出生地");
            writer.addHeaderAlias("army", "兵役情况");

//            // 合并单元格后的标题行，使用默认标题样式
//            writer.merge(2, "学员信息");
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(userList, true);
            //out为OutputStream，需要写出到的目标流
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            String name = "xueyuan";
            response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");

            ServletOutputStream out = null;
            try {
                out = response.getOutputStream();
                writer.flush(out, true);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭writer，释放内存
                writer.close();
            }
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        }
    }


    private List<User> getUserList(List<User> userList) {
        List<Level> keyValues = levelService.getLevelList();
        Map<Integer, String> map =
                keyValues.stream().collect(Collectors.toMap(
                        Level::getLevel,
                        Level::getLevelName,
                        (key1, key2) -> key2
                ));

        for (User user : userList) {
            user.getUserInfoDetail(user);
            String levelName = map.get(user.getUserLevel());
            user.setLevelName(levelName);
        }
        return userList;
    }
}
